//
//  WriteDetailController.m
//  DIYCityKorea
//
//  Created by 훈준 박 on 10. 4. 27..
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import	"DIYCityKoreaAppDelegate.h"
#import "WriteDetailController.h"
#import "AfterPostController.h"
#import "ASIHTTPRequest.h"

#define kOFFSET_FOR_KEYBOARD 60.0
#define kDETAIL_PLACEHOLDER_MESSAGE @"제보 내용을 입력해 주세요."

@implementation WriteDetailController

@synthesize takenPhotoImageView;
@synthesize emailField;
@synthesize detailField;
@synthesize reportBtn;

@synthesize keyboardShown;
@synthesize locationUpdated;
@synthesize locationManager;
@synthesize startingPoint;
@synthesize indicatorSubViewController;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

#pragma mark IndicatorHelper
- (void) showIndicatorView:(NSString*)message {
	self.indicatorSubViewController = [[IndicatorViewController alloc] 
									   initWithNibName:@"IndicatorViewController" 
									   withMessage:message
									   bundle:nil];
	
	[self.view addSubview:self.indicatorSubViewController.view];		
}

- (void) removeIndicatorView {
	[self.indicatorSubViewController.view removeFromSuperview];
}

#pragma mark locationManager protocol
- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation {
	
	/***** Fail TEST *****/
//	[self locationManager:manager didFailWithError:nil];
//	return;
	/***** ~Fail TEST *****/
	
	if (!self.locationUpdated) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"성공" 
														message:@"위치 정보를\n 성공적으로 얻어 왔습니다." 
													   delegate:nil 
											  cancelButtonTitle:@"확인" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
		[reportBtn setEnabled:YES];
	}
	
	self.locationUpdated = YES;
	[locationManager stopUpdatingLocation];

	DIYCityKoreaAppDelegate *delegate;
	delegate = [[UIApplication sharedApplication] delegate];
	delegate.latString = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.latitude];
	delegate.lngString = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.longitude];
	
	[self removeIndicatorView];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
	if (!self.locationUpdated) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"실패" 
														message:@"위치 정보를\n얻어오지 못했습니다.\n다시 시도할까요?" 
													   delegate:self 
											  cancelButtonTitle:nil
											  otherButtonTitles:@"다시시도",@"취소", nil];
		[alert show];
		[alert release];
	}
	self.locationUpdated = NO;
	[self removeIndicatorView];
}

/* TODO : If fail to get location */
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0) {
		[self showIndicatorView:@"위치정보를 얻어오고 있습니다."];
		[self.locationManager startUpdatingLocation];
	}
}


#pragma mark Moving view when keyboard shown
-(IBAction)hiddenKeyboard:(id)sender {
	[self.emailField resignFirstResponder];
	[self.detailField resignFirstResponder];
}

-(void)setViewMovedUp:(BOOL)movedUp isDetail:(BOOL)isDetail
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5]; // if you want to slide up the view
	CGRect rect = self.view.frame;
    int size;
	
	if (isDetail) {
		size = kOFFSET_FOR_KEYBOARD+110;
	} else {
		size = kOFFSET_FOR_KEYBOARD+13;
	}

	if (movedUp) {
        rect.origin.y -= size;
        rect.size.height += size;
    } else {
        rect.origin.y += size;
        rect.size.height -= size;
    }
    self.view.frame = rect;
	
    [UIView commitAnimations];
	
//	NSLog([[NSString alloc] initWithFormat:@"%f", self.view.frame.origin.y]);
}

- (void)textViewDidBeginEditing:(UITextView *)textView 
{
	[self.emailField setEnabled:NO];

	BOOL shouldReset = [self.detailField.text isEqualToString:kDETAIL_PLACEHOLDER_MESSAGE];
	if (shouldReset) {
		[self.detailField setTextColor:[UIColor	blackColor]];
		self.detailField.text = @"";
	}
	
	if (keyboardShown)
		return;

	if  (self.view.frame.origin.y >= 0) {
		[self setViewMovedUp:YES isDetail:YES];
		keyboardShown = YES;
	}	
}

- (void)textViewDidEndEditing:(UITextView *)textView 
{
	NSString *details = [self.detailField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	if ([details isEqualToString:@""]) {
		self.detailField.text = kDETAIL_PLACEHOLDER_MESSAGE;
		[self.detailField setTextColor:[UIColor	lightGrayColor]];
	}
	
	[self.emailField setEnabled:YES];
	if  (self.view.frame.origin.y < 0) {
		[self setViewMovedUp:NO isDetail:YES];
	}
	keyboardShown = NO;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[emailField resignFirstResponder];
	return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{	
	if (keyboardShown)
		return;
	
	if  (self.view.frame.origin.y >= 0) {
		keyboardShown = YES;
		[self setViewMovedUp:YES isDetail:NO];
	}
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
	if  (self.view.frame.origin.y < 0) {
		[self setViewMovedUp:NO isDetail:NO];
	}
	keyboardShown = NO;
}

- (void)setLeftRightBarButtonItem {
	UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"취소" 
																  style:UIBarButtonItemStylePlain 
																 target:self 
																 action:@selector(cancelPost:)];
	
	self.reportBtn = [[UIBarButtonItem alloc] initWithTitle:@"전송" 
												 style:UIBarButtonItemStylePlain 
											    target:self 
											    action:@selector(postDetail:)];
	
	[reportBtn setEnabled:NO];
	
	[self.navigationController.navigationBar setHidden:NO];
	self.title =  @"제보내용";
	
	self.navigationItem.leftBarButtonItem = cancelBtn;
	[cancelBtn release];
	
	self.navigationItem.rightBarButtonItem = reportBtn;
	[reportBtn release];	
}

- (BOOL)validateEmailString:(NSString*)emailString {
	NSString *emailRegEx =
    @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
    @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
    @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
    @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
    @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
    @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
    @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
	
	NSPredicate *regExPredicate =
	[NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
	BOOL emailValidate = [regExPredicate evaluateWithObject:emailString];	

	return emailValidate;
}

- (BOOL)validatePostField {
	/* Trim white space */
	NSString *email = [self.emailField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	NSString *details = [self.detailField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

	
	if ([details isEqualToString:@""] || [details isEqualToString:kDETAIL_PLACEHOLDER_MESSAGE]) { /* Empty detail field */
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"오류" 
														message:@"내용을 입력해 주세요" 
													   delegate:nil 
											  cancelButtonTitle:@"확인" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
		
		return NO;
	}
	
	if ([email isEqualToString:@""]) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"오류" 
														message:@"메일주소를 입력해 주세요" 
													   delegate:nil 
											  cancelButtonTitle:@"확인" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
		
		return NO;
	}
	
	if (![self validateEmailString:email]) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"오류" 
														message:@"메일주소 형식이 맞지 않습니다" 
													   delegate:nil 
											  cancelButtonTitle:@"확인" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
		
		return NO;
	}
	
	return YES;
}

#pragma mark Post or Calcel actions
- (void)cancelPost:(id)sender {
	[self.navigationController.navigationBar setHidden:YES];
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)postDetail:(id)sender {
	BOOL valid = [self validatePostField];
	if (valid) {
		DIYCityKoreaAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
		[self showIndicatorView:@"전송중..."];

		delegate.detailString = self.detailField.text;
		delegate.emailString = self.emailField.text;

		
		/* Remember recent email address */
		NSMutableArray *array = [[NSMutableArray alloc] init];
		[array addObject:delegate.emailString];
		[array writeToFile:[self dataFilePath] atomically:YES];
		[array release];
		/* ~Remember recent email address */
		
		
		/* TODO HTTP SEND AND RESULT */ 
		ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[[NSURL alloc] initWithString:DIYCITY_POST_ADDRESS]];
		[request setPostValue:delegate.latString forKey:@"lat"];
		[request setPostValue:delegate.lngString forKey:@"lng"];
		[request setPostValue:delegate.detailString forKey:@"details"];
		[request setPostValue:delegate.emailString forKey:@"email"];
		[request setPostValue:@"iPhone" forKey:@"service_type"];
		[request setFile:delegate.imageFilePath forKey:@"photo"];
		[request setDelegate:self];
		[request startAsynchronous];
		[request setTimeOutSeconds:30];
		[self.reportBtn setEnabled:NO];
	} else {
		return;
	}
}


#pragma mark ASIHTTPRequest call back
- (void)requestFinished:(ASIHTTPRequest *)request
{
	/*** FAIL TEST ***/
//	[self requestFailed:request];
//	return;
	/*** ~FAIL TEST ***/
	
	[self removeIndicatorView];	
	NSString *responseString = [request responseString];	

	if ([responseString isEqualToString:@"SUCCESS"]) {
		AfterPostController *afterPostController = [[AfterPostController alloc] initWithNibName:@"AfterPostController" bundle:nil];
		[self.navigationController pushViewController:afterPostController animated:YES];
		[afterPostController release];						
	} else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"실패" 
														message:@"전송에 실패 했습니다.\n다시 시도해 주세요." 
													   delegate:nil 
											  cancelButtonTitle:@"확인" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];		
	}
	[self.reportBtn setEnabled:YES];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	[self removeIndicatorView];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"전송에 실패 했습니다.\n 다시 시도해 주세요." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	[alert release];
	[self.reportBtn setEnabled:YES];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (NSString*)dataFilePath {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	return [documentsDirectory stringByAppendingPathComponent:kFilename];
}



- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidLoad {
	DIYCityKoreaAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[self setLeftRightBarButtonItem];
//	[self registerForKeyboardNotifications];
	self.locationUpdated = NO;
	self.keyboardShown = NO;
	self.emailField.delegate = self;
	self.detailField.delegate = self;

	/* For place holder */
	[self.detailField setTextColor:[UIColor	lightGrayColor]];
	[self.detailField setFont:[UIFont fontWithName:@"AppleGothic" size:18.0f]];

	/* Saved email */
	NSString *filePath = [self dataFilePath];
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
		NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
		self.emailField.text = [array objectAtIndex:0];
		[array release];
	}
//	[self.emailField setText:value];
//	[plistDict release];
	
	
	/* Get location */
	self.locationManager = [[CLLocationManager alloc] init];
	locationManager.delegate = self;
	locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	[locationManager startUpdatingLocation];
	UIImage *newImage = [[UIImage alloc] initWithData:delegate.takenPhoto];
	[self.takenPhotoImageView setImage:newImage];
	
	[self showIndicatorView:@"위치정보를 얻어오고 있습니다."];
    [super viewDidLoad];
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.takenPhotoImageView = nil;
	self.emailField = nil;
	self.detailField = nil;
	self.indicatorSubViewController = nil;
	
	self.locationManager = nil;
	self.startingPoint = nil;
	self.reportBtn = nil;
}


- (void)dealloc {
	[takenPhotoImageView release];
	[emailField release];
	[detailField release];
	[locationManager release];
	[startingPoint release];
	[indicatorSubViewController release];
	[reportBtn release];

    [super dealloc];
}


@end
